package cn.achao.csr.chat.core.mq.consumer;

import cn.achao.csr.api.model.dto.MsgSendMessageDTO;
import cn.achao.csr.api.model.entity.ChatMsg;
import cn.achao.csr.api.model.entity.ChatRoom;
import cn.achao.csr.api.model.resp.ChatMessageResp;
import cn.achao.csr.base.constant.RockMqKeyConstants;
import cn.achao.csr.chat.core.build.WSAdapter;
import cn.achao.csr.chat.dao.ChatMsgDao;
import cn.achao.csr.chat.dao.ChatRoomDao;
import cn.achao.csr.chat.service.ChatService;
import cn.achao.csr.chat.service.cache.HotRoomCacheService;
import cn.achao.csr.chat.service.impl.PushServiceImpl;
import com.alibaba.fastjson2.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

/**
 * Description: 发送消息更新房间收信箱，并同步给房间成员信箱
 * Author: achao
 */
@Slf4j
@Component
@RequiredArgsConstructor
@RocketMQMessageListener(consumerGroup = RockMqKeyConstants.SEND_MSG_GROUP, topic = RockMqKeyConstants.SEND_MSG_TOPIC)
public class MsgSendConsumer implements RocketMQListener<MsgSendMessageDTO> {

    private final ChatMsgDao msgDao;
    private final ChatRoomDao roomDao;
    private final ChatService chatService;
    private final PushServiceImpl pushService;
    private final HotRoomCacheService hotRoomCacheService;

    @Override
    public void onMessage(MsgSendMessageDTO dto) {
        log.info("mq主题csr_chat_send_msg收到消息：{}", JSON.toJSONString(dto));
        ChatMsg msg = msgDao.getById(dto.getMsgId());
        ChatRoom room = roomDao.getById(msg.getRoomId());
        //ChatMessageDTO msgDTO = chatService.getMsgResp(msg, null);
        ChatMessageResp msgDTO = chatService.getMsgResp(msg, null);
        //所有房间更新房间最新消息
        //roomDao.refreshActiveTime(room.getId(), msg.getId(), msg.getCreateTime());
        if (room.isHotRoom()) {
            hotRoomCacheService.refreshActiveTime(room.getId(), msg.getCreateTime());

            pushService.sendPushMsg(WSAdapter.buildMsgSend(msgDTO));
        } else {

        }
    }


}
